package com.sporch.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author czy
 * @date 2019/5/30
 */
@Service
public class HelloService {
    @Resource(name = "ribbonRestTemplate")
    RestTemplate ribbonRestTemplate;

    @Resource(name = "commonRestTemplate")
    RestTemplate commonRestTemplate;

    /**
     * 远程调用service-hi微服务中的/hi接口
     * @param name
     * @return
     * @HystrixCommand 该注解对该方法创建了熔断器的功能，并指定了fallbackMethod熔断方法，
     * 熔断方法直接返回了一个字符串，字符串为"hi,"+name+",sorry,error!"，
     */
    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        return ribbonRestTemplate.getForObject("http://service-hi/hi?name="+name,String.class);
    }

    /**
     * 熔断方法
     * @param name
     * @return
     */
    public String hiError(String name) {
        return "hi,"+name+",sorry,error!";
    }

    /**
     * send restful request by common restTemplate
     * @param name
     * @return
     */
    public String commonHiService(String name) {
        return commonRestTemplate.getForObject("http://localhost:8763/hi?name="+name,String.class);
    }
}
